/**
 * 智能体编辑页面组件
 * 
 * 功能特性：
 * - 智能体信息编辑
 * - 模型配置选择
 * - 提示词模板选择
 * - 高级参数配置
 * - 表单验证和错误处理
 * - 实时预览功能
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Select, 
  Button, 
  message, 
  Space, 
  InputNumber,
  Switch,
  Radio,
  Divider,
  Alert,
  Spin,
  Tag,
  Tooltip
} from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { 
  SaveOutlined, 
  ArrowLeftOutlined, 
  ReloadOutlined,
  EyeOutlined,
  SettingOutlined
} from '@ant-design/icons';
import agentService, { AgentStatus, AgentType } from '@services/agentService';

const { TextArea } = Input;
const { Option } = Select;
const { Group: RadioGroup } = Radio;

interface ModelConfig {
  id: string;
  name: string;
  provider: string;
  model: string;
  maxTokens: number;
  temperature: number;
  isActive: boolean;
}

interface PromptTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  template: string;
  isActive: boolean;
}

interface AgentFormData {
  name: string;
  description: string;
  agentType: AgentType;
  systemPrompt: string;
  configuration: string;
  modelConfigId?: string;
  promptTemplateId?: string;
  tags: string;
  maxTokens: number;
  temperature: number;
  timeoutSeconds: number;
  isActive: boolean;
}

const AgentEdit: React.FC = () => {
  const [form] = Form.useForm<AgentFormData>();
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [modelConfigs, setModelConfigs] = useState<ModelConfig[]>([]);
  const [promptTemplates, setPromptTemplates] = useState<PromptTemplate[]>([]);
  const [initialLoading, setInitialLoading] = useState(true);
  const [showAdvanced, setShowAdvanced] = useState(false);

  useEffect(() => {
    if (id) {
      loadAgent();
    }
    loadModelConfigs();
    loadPromptTemplates();
  }, [id]);

  const loadAgent = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await agentService.getAgent(id);
      
      // 设置表单初始值
      form.setFieldsValue({
        name: response.name,
        description: response.description,
        agentType: response.agentType,
        systemPrompt: response.systemPrompt,
        configuration: response.configuration,
        modelConfigId: response.modelConfigId,
        promptTemplateId: response.promptTemplateId,
        tags: response.tags,
        maxTokens: response.maxTokens,
        temperature: response.temperature,
        timeoutSeconds: response.timeoutSeconds,
        isActive: response.isActive
      });
    } catch (error) {
      message.error('加载智能体信息失败');
      navigate('/agents');
    } finally {
      setLoading(false);
      setInitialLoading(false);
    }
  };

  const loadModelConfigs = async () => {
    try {
      const response = await agentService.getModelConfigs({
        isActive: true,
        maxResultCount: 100,
      });
      setModelConfigs(response.items);
    } catch (error) {
      message.error('加载模型配置失败');
    }
  };

  const loadPromptTemplates = async () => {
    try {
      const response = await agentService.getPromptTemplates({
        isActive: true,
        maxResultCount: 100,
      });
      setPromptTemplates(response.items);
    } catch (error) {
      message.error('加载提示词模板失败');
    }
  };

  const handleModelConfigChange = (configId: string) => {
    const config = modelConfigs.find(c => c.id === configId);
    if (config) {
      form.setFieldsValue({
        maxTokens: config.maxTokens,
        temperature: config.temperature
      });
    }
  };

  const handlePromptTemplateChange = (templateId: string) => {
    const template = promptTemplates.find(t => t.id === templateId);
    if (template) {
      form.setFieldsValue({
        systemPrompt: template.template
      });
    }
  };

  const handleSubmit = async (values: AgentFormData) => {
    if (!id) return;
    
    try {
      setSaving(true);
      await agentService.updateAgent(id, values);
      message.success('更新智能体成功');
      navigate(`/agents/${id}`);
    } catch (error) {
      message.error('更新智能体失败');
    } finally {
      setSaving(false);
    }
  };

  const handleTestPrompt = () => {
    const systemPrompt = form.getFieldValue('systemPrompt');
    if (systemPrompt) {
      // 这里可以实现提示词预览功能
      message.info('提示词预览功能开发中...');
    }
  };

  const getAgentTypeColor = (type: AgentType) => {
    const colors = {
      [AgentType.Chat]: 'blue',
      [AgentType.Assistant]: 'green',
      [AgentType.Analyst]: 'orange',
      [AgentType.Creative]: 'purple',
      [AgentType.Custom]: 'default'
    };
    return colors[type] || 'default';
  };

  const getAgentTypeText = (type: AgentType) => {
    const texts = {
      [AgentType.Chat]: '聊天',
      [AgentType.Assistant]: '助手',
      [AgentType.Analyst]: '分析',
      [AgentType.Creative]: '创意',
      [AgentType.Custom]: '自定义'
    };
    return texts[type] || '未知';
  };

  if (initialLoading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <Card
        title="编辑智能体"
        extra={
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(`/agents/${id}`)}>
              返回详情
            </Button>
            <Button icon={<ReloadOutlined />} onClick={loadAgent} loading={loading}>
              重置
            </Button>
          </Space>
        }
      >
        <Alert
          message="编辑智能体信息"
          description="修改智能体的基本信息、配置参数和运行设置。部分配置更改可能需要重启智能体才能生效。"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          autoComplete="off"
        >
          {/* 基本信息 */}
          <Card 
            title="基本信息" 
            size="small" 
            style={{ marginBottom: 16 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            <Form.Item
              name="name"
              label="智能体名称"
              rules={[
                { required: true, message: '请输入智能体名称' },
                { min: 2, max: 50, message: '名称长度在2-50个字符之间' }
              ]}
            >
              <Input placeholder="请输入智能体名称" />
            </Form.Item>

            <Form.Item
              name="description"
              label="描述"
              rules={[
                { required: true, message: '请输入描述' },
                { max: 500, message: '描述最多500个字符' }
              ]}
            >
              <TextArea 
                rows={3} 
                placeholder="请输入智能体描述"
                maxLength={500}
                showCount
              />
            </Form.Item>

            <Form.Item
              name="agentType"
              label="智能体类型"
              rules={[{ required: true, message: '请选择智能体类型' }]}
            >
              <RadioGroup>
                {Object.values(AgentType).filter(type => typeof type === 'string').map(type => (
                  <Radio key={type} value={type as AgentType}>
                    <Tag color={getAgentTypeColor(type as AgentType)}>
                      {getAgentTypeText(type as AgentType)}
                    </Tag>
                  </Radio>
                ))}
              </RadioGroup>
            </Form.Item>
          </Card>

          {/* AI配置 */}
          <Card 
            title="AI配置" 
            size="small" 
            style={{ marginBottom: 16 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            <Form.Item
              name="systemPrompt"
              label="系统提示词"
              rules={[
                { required: true, message: '请输入系统提示词' },
                { min: 10, message: '系统提示词至少10个字符' }
              ]}
            >
              <TextArea 
                rows={8} 
                placeholder="请输入系统提示词"
                maxLength={2000}
                showCount
              />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button 
                  icon={<EyeOutlined />}
                  onClick={handleTestPrompt}
                  size="small"
                >
                  预览提示词
                </Button>
                <Tooltip title="选择提示词模板将覆盖当前系统提示词">
                  <Tag color="orange">提示：选择模板将覆盖当前提示词</Tag>
                </Tooltip>
              </Space>
            </Form.Item>

            <Form.Item
              name="modelConfigId"
              label="模型配置"
              rules={[{ required: true, message: '请选择模型配置' }]}
            >
              <Select 
                placeholder="请选择模型配置"
                onChange={handleModelConfigChange}
              >
                {modelConfigs.map(config => (
                  <Option key={config.id} value={config.id}>
                    <Space>
                      <span>{config.name}</span>
                      <Tag>{config.provider}</Tag>
                      <Tag>{config.model}</Tag>
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="promptTemplateId"
              label="提示词模板"
            >
              <Select 
                placeholder="请选择提示词模板" 
                allowClear
                onChange={handlePromptTemplateChange}
              >
                {promptTemplates.map(template => (
                  <Option key={template.id} value={template.id}>
                    <Space>
                      <span>{template.name}</span>
                      <Tag>{template.category}</Tag>
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Card>

          {/* 高级配置 */}
          <Card 
            title={
              <Space>
                <SettingOutlined />
                高级配置
                <Button 
                  type="link" 
                  onClick={() => setShowAdvanced(!showAdvanced)}
                >
                  {showAdvanced ? '收起' : '展开'}
                </Button>
              </Space>
            }
            size="small"
            style={{ marginBottom: 16 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            {showAdvanced && (
              <>
                <Form.Item
                  name="configuration"
                  label="扩展配置 (JSON)"
                  rules={[
                    {
                      validator: (_, value) => {
                        if (value && value.trim()) {
                          try {
                            JSON.parse(value);
                          } catch {
                            return Promise.reject('请输入有效的JSON格式');
                          }
                        }
                        return Promise.resolve();
                      }
                    }
                  ]}
                >
                  <TextArea 
                    rows={6} 
                    placeholder='请输入JSON格式的扩展配置，例如：{"key": "value"}'
                  />
                </Form.Item>

                <Form.Item
                  name="tags"
                  label="标签"
                >
                  <Input placeholder="请输入标签，用逗号分隔" />
                </Form.Item>

                <Divider />

                <Form.Item
                  name="maxTokens"
                  label="最大Token数"
                  rules={[
                    { required: true, message: '请输入最大Token数' },
                    { type: 'number', min: 1, max: 32000, message: 'Token数在1-32000之间' }
                  ]}
                >
                  <InputNumber 
                    min={1} 
                    max={32000}
                    style={{ width: '100%' }}
                    placeholder="最大Token数"
                  />
                </Form.Item>

                <Form.Item
                  name="temperature"
                  label="温度参数"
                  rules={[
                    { required: true, message: '请输入温度参数' },
                    { type: 'number', min: 0, max: 2, message: '温度参数在0-2之间' }
                  ]}
                >
                  <InputNumber 
                    min={0} 
                    max={2}
                    step={0.1}
                    style={{ width: '100%' }}
                    placeholder="温度参数 (0.0-2.0)"
                  />
                </Form.Item>

                <Form.Item
                  name="timeoutSeconds"
                  label="超时时间（秒）"
                  rules={[
                    { required: true, message: '请输入超时时间' },
                    { type: 'number', min: 1, max: 300, message: '超时时间在1-300秒之间' }
                  ]}
                >
                  <InputNumber 
                    min={1} 
                    max={300}
                    style={{ width: '100%' }}
                    placeholder="超时时间"
                  />
                </Form.Item>
              </>
            )}
          </Card>

          {/* 状态设置 */}
          <Card 
            title="状态设置" 
            size="small" 
            style={{ marginBottom: 24 }}
            headStyle={{ backgroundColor: '#f5f5f5' }}
          >
            <Form.Item
              name="isActive"
              label="激活状态"
              valuePropName="checked"
            >
              <Switch 
                checkedChildren="激活" 
                unCheckedChildren="禁用" 
              />
            </Form.Item>
          </Card>

          {/* 操作按钮 */}
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={saving}
                icon={<SaveOutlined />}
              >
                保存更改
              </Button>
              <Button onClick={() => navigate(`/agents/${id}`)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default AgentEdit;